package com.example.lenovo.retrofit_test.exception.subscriber;

import android.app.ProgressDialog;
import android.content.Context;

import com.example.lenovo.retrofit_test.exception.RxErrorHandler;

/**
 * Created by lenovo on 2017/5/10.
 */

public abstract class ProgressDialogSubcriber<T> extends ErrorHandlerSubscriber<T> {

    private ProgressDialog mProgressdialog;
    private Context mContext;


    public ProgressDialogSubcriber(RxErrorHandler mRxErrorHandler, Context mContext) {
        super(mRxErrorHandler);
        this.mContext=mContext;
        initProgressDialog();
    }

    // 如果子类,继承此方法,并且返回为false。则不再弹框。
    protected boolean isShowProgressDialog() {
        return true;
    }

    @Override
    public void onStart() {
        if (isShowProgressDialog()) {
            showProgressDialog();
        }
    }

    @Override
    public void onCompleted() {
        if (isShowProgressDialog()) {
            dismissProgressDialog();
        }
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        if (isShowProgressDialog()) {
            dismissProgressDialog();
        }
    }


    private void initProgressDialog() {
        if (mProgressdialog == null) {
            mProgressdialog = new ProgressDialog(mContext);
            mProgressdialog.setMessage("loading....");
        }
    }

    private void showProgressDialog() {
        if (isShowProgressDialog()) {
            initProgressDialog();
            if (mProgressdialog != null && !mProgressdialog.isShowing()) {
                mProgressdialog.show();
            }
        }
    }


    private void dismissProgressDialog() {
        if (isShowProgressDialog()) {
            if (mProgressdialog != null) {
                mProgressdialog.dismiss();
            }
        }
    }
}
